package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Auth;
import com.atguigu.crowd.service.AuthService;
import com.atguigu.crowd.entity.Role;
import com.atguigu.crowd.service.AdminService;
import com.atguigu.crowd.service.RoleService;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * @author yzt
 * @create 2021-09-13 21:57
 */
@Controller
public class AssignHandler {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @ResponseBody
    @RequestMapping("/assign/auth/to/role")
    public ResultEntity<String> assignAuthToRole(@RequestBody Map<String,List<Integer>> map){
        authService.saveAuthList(map);
        return ResultEntity.successWithoutData();
    }
    @ResponseBody
    @RequestMapping("/assign/get/all/auth")
    public ResultEntity<List<Auth>> assignGetAllAuth(){
        List<Auth> authList = authService.getAll();
        return ResultEntity.successWithData(authList);
    }

    @ResponseBody
    @RequestMapping("/assign/get/auth/by/id")
    public ResultEntity<List<Integer>> assignGetAuthById(@RequestParam("roleId") Integer roleId){
        List<Integer> authIdList = authService.getAuthByRoleId(roleId);
        return ResultEntity.successWithData(authIdList);
    }

    @RequestMapping("/assign/to/role")
    public String assignToRole(@RequestParam("adminId") Integer adminId, Model model){
        //获取已分配的角色
        List<Role> assignedRoleList = roleService.getAssignedRole(adminId);
        //获取未分配的角色
        List<Role> unAssignedRoleList = roleService.getUnAssignedRole(adminId);
        model.addAttribute("assignedRoleList",assignedRoleList);
        model.addAttribute("unAssignedRoleList",unAssignedRoleList);

        return "assign-role";
    }

    @RequestMapping("/assign/do/role/assign")
    public String assignDoRole(@RequestParam("adminId") Integer adminId,
                               @RequestParam("pageNum") Integer pageNum,
                               @RequestParam("keyword") String keyword,
                               @RequestParam(value = "roleList",required = false) List<Integer> roleList){

        roleService.saveAdminRoleRelationship(adminId,roleList);
        return "redirect:/admin/get/page?pageNum="+pageNum+"&keyword="+keyword;
    }
}
